package com.qingcheng.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qingcheng.util.BCrypt;
import com.qingcheng.dao.AdminMapper;
import com.qingcheng.dao.AdminRoleIdsMapper;
import com.qingcheng.dao.RoleMapper;
import com.qingcheng.entity.PageResult;
import com.qingcheng.pojo.system.Admin;
import com.qingcheng.pojo.system.AdminRoleIds;
import com.qingcheng.pojo.system.AdminRoleResult;
import com.qingcheng.pojo.system.Role;
import com.qingcheng.service.system.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = AdminService.class)
public class AdminServiceImpl implements AdminService {

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private AdminRoleIdsMapper adminRoleIdsMapper;

    @Autowired
    private RoleMapper roleMapper;

    /**
     * 返回全部记录
     *
     * @return
     */
    public List<Admin> findAll() {
        return adminMapper.selectAll();
    }

    /**
     * 分页查询
     *
     * @param page 页码
     * @param size 每页记录数
     * @return 分页结果
     */
    public PageResult<Admin> findPage(int page, int size) {
        PageHelper.startPage(page, size);
        Page<Admin> admins = (Page<Admin>) adminMapper.selectAll();
        return new PageResult<Admin>(admins.getTotal(), admins.getResult());
    }

    /**
     * 条件查询
     *
     * @param searchMap 查询条件
     * @return
     */
    public List<Admin> findList(Map<String, Object> searchMap) {
        Example example = createExample(searchMap);
        return adminMapper.selectByExample(example);
    }

    /**
     * 分页+条件查询
     *
     * @param searchMap
     * @param page
     * @param size
     * @return
     */
    public PageResult<Admin> findPage(Map<String, Object> searchMap, int page, int size) {
        PageHelper.startPage(page, size);
        Example example = createExample(searchMap);
        Page<Admin> admins = (Page<Admin>) adminMapper.selectByExample(example);
        return new PageResult<Admin>(admins.getTotal(), admins.getResult());
    }

    /**
     * 根据Id查询
     *
     * @param id
     * @return
     */
    @Transactional
    public AdminRoleResult findByAdminId(Integer id) {
       /* //通过用户ID找出用户
        Admin admin = adminMapper.selectByPrimaryKey(id);
        AdminRoleResult adminRoleResult = new AdminRoleResult();
        //通过用户ID找出所以用户ID和角色ID
        Example example = new Example(AdminRoleIds.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("adminId", id);
        List<AdminRoleIds> adminRoleIds = adminRoleIdsMapper.selectByExample(example);
        List<Integer> roleIds = new ArrayList<>();
        for (AdminRoleIds adminRoleId : adminRoleIds) {
            //循环遍历中间表对象得到所有角色ID
                 roleIds.add(adminRoleId.getRoleId());
        }
        adminRoleResult.setAdmin(admin);
        Example example1 = new Example(Role.class);
        Example.Criteria criteria1 = example1.createCriteria();
        criteria1.andEqualTo("id",roleIds);
        List<Role> roles = roleMapper.selectByExample(example1);*/
        //通过ID找出admin用户
        Admin admin = adminMapper.selectByPrimaryKey(id);
        AdminRoleResult adminRoleResult = new AdminRoleResult();
        adminRoleResult.setAdmin(admin);
        List<Role> roles = roleMapper.findByAdminId(id);
        adminRoleResult.setRoles(roles);
        return adminRoleResult;
    }

    /**
     * 新增
     *
     * @param admin
     */
    @Transactional
    public void add(Admin admin, List<Role> roles) {

        AdminRoleIds adminRoleIds = new AdminRoleIds();
        for (Role role : roles) {
            //循环加入角色Id
            adminRoleIds.setAdminId(admin.getId());
            adminRoleIds.setRoleId(role.getId());
            adminRoleIdsMapper.insert(adminRoleIds);
        }
        //加密密码
        String hashpw = BCrypt.hashpw(admin.getPassword(), BCrypt.gensalt());
        admin.setPassword(hashpw);
        adminMapper.insert(admin);
    }

    /**
     * 修改
     *
     * @param adminRoleResult
     */
    @Transactional
    public void update(AdminRoleResult adminRoleResult) {
        Admin admin = adminRoleResult.getAdmin();
        if (admin.getPassword() != null) {
            String hashpw = BCrypt.hashpw(admin.getPassword(), BCrypt.gensalt());
            admin.setPassword(hashpw);
        }
        adminMapper.updateByPrimaryKeySelective(admin);
        //根据用户ID先删除所以角色id和用户ID
        Example example = new Example(AdminRoleIds.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("adminId", admin.getId());
        adminRoleIdsMapper.deleteByExample(example);
        //定义一个新的中间表对象 加入用户ID和 角色ID

        //获得roleIds对象 来获取roleId
        List<Role> roles = adminRoleResult.getRoles();
        for (Role role : roles) {
            AdminRoleIds adminRoleIds = new AdminRoleIds();
            adminRoleIds.setAdminId(admin.getId());
            adminRoleIds.setRoleId(role.getId());
            adminRoleIdsMapper.insert(adminRoleIds);
        }

    }

    /**
     * 删除
     *
     * @param id
     */
    public void delete(Integer id) {
        adminMapper.deleteByPrimaryKey(id);
    }

    /**
     * 根据原密码修改
     *
     * @param map
     */
    @Transactional
    public void updatePassword(Map<String, String> map) {
        //创建一个Map从数据库读取该用户名的信息
        Map map2 = new HashMap<>();
        map2.put("loginName", map.get("username"));
        map2.put("status", 1);
        List<Admin> list = findList(map2);
        if (list.size() == 0) {
            throw new RuntimeException("用户不存在");
        }
        //BCrypt.checkpw方法判断输入的原密码是否和数据库的盐匹配
        boolean checkpw = BCrypt.checkpw(map.get("oldPassword"), list.get(0).getPassword());

        if (checkpw == false) {
            throw new RuntimeException("输入的原密码有误");
        }
        if (checkpw == true) {
            //使用BCrypt.hashpw创建随机盐
            String hashpw = BCrypt.hashpw(map.get("newPassword"), BCrypt.gensalt());
            list.get(0).setPassword(hashpw);
            adminMapper.updateByPrimaryKeySelective(list.get(0));
        }


    }

    /**
     * 构建查询条件
     *
     * @param searchMap
     * @return
     */
    private Example createExample(Map<String, Object> searchMap) {
        Example example = new Example(Admin.class);
        Example.Criteria criteria = example.createCriteria();
        if (searchMap != null) {
            // 用户名
            if (searchMap.get("loginName") != null && !"".equals(searchMap.get("loginName"))) {
                //criteria.andLike("loginName","%"+searchMap.get("loginName")+"%");
                criteria.andEqualTo("loginName", searchMap.get("loginName"));
            }
            // 密码
            if (searchMap.get("password") != null && !"".equals(searchMap.get("password"))) {
                criteria.andLike("password", "%" + searchMap.get("password") + "%");
            }
            // 状态
            if (searchMap.get("status") != null && !"".equals(searchMap.get("status"))) {
                //  criteria.andLike("status","%"+searchMap.get("status")+"%");
                criteria.andEqualTo("status", searchMap.get("status"));
            }

            // id
            if (searchMap.get("id") != null) {
                criteria.andEqualTo("id", searchMap.get("id"));
            }

        }
        return example;
    }

}
